package com.shiyi.controller;

import com.shiyi.exceptions.MyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * ExceptionHandler在当前类和全局的命中范围
 * 当前类指定异常->当前类Exception->全局类指定异常->全局类Exception
 * @author wangzhanshuai
 * @date 2021/1/23 7:24 下午
 * @since 1.0
 */
@Controller
public class ExceptionController {

    @RequestMapping("/exception")
    public String testException() {
        int i = 1 / 0;
        return "success";
    }

    @RequestMapping("/exception2")
    public String testException2(@RequestParam("abc") String abc) {
        if("abc".equals(abc)) {
            throw new MyException();
        }
        return "success";
    }

    @ExceptionHandler(ArithmeticException.class)
    public ModelAndView handleException(Exception exception) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("exec", exception);
        return modelAndView;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException2(Exception exception) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("exec", exception);
        return modelAndView;
    }
}
